package zz.extjs.servlet;

import com.jspsmart.upload.File;
import com.jspsmart.upload.Files;
import com.jspsmart.upload.SmartUpload;
import com.teetaa.util.ImageHepler;

import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import javax.imageio.ImageIO;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UpLoadUserHeadImage extends HttpServlet {
	private ServletConfig config = null;
	//private String FileName = "uploadtmp"; // null; //固定上传文件名称，即只保留1张原始照片
	private String FileName = null; 
	private String sPath = "UploadPhoto"; // 必须有此文件夹存在，否则出错

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html; charset=utf-8");
		//PrintWriter out = response.getWriter();

		// 登录检查
		Object zz = request.getSession().getAttribute("user1");

		if (zz == null) { // 先检查用户是否处于登入状态
			response.sendRedirect("logout.jsp");
			return;
		}
		
		//get方法用于处理图片旋转等
		String pbid = request.getParameter("pbid")==null?(String)request.getAttribute("pbid"):request.getParameter("pbid");
		pbid = pbid==null?"":"&pbid="+pbid;

		int degree = request.getParameter("turnimg")!=null?Integer.parseInt(request.getParameter("turnimg")):0;
		this.FileName = request.getParameter("imgfile");
		this.FileName = this.FileName!=null?this.FileName.substring(0, this.FileName.lastIndexOf(".")):null;

		java.io.File old = this.FileName!=null ? new java.io.File(request.getRealPath("/") + "/"
				+ this.sPath + "/" + this.FileName + ".jpg" ) : null;
		if(old==null || !(old.exists()) ){
			response.getWriter().print("提交图片信息出错！");
			return;
		}
		BufferedImage img = ImageIO.read(old);
		java.io.File f = new java.io.File(old.getParent()+"/"+this.FileName+".jpg"); 
		while(f.exists()){
			this.FileName += "1";
			f = new java.io.File(old.getParent()+"/"+this.FileName+".jpg");
		}
		ImageHepler.rotateImage(img, degree,f);

		//ImageIO.write(rotateImage(img, -90), "JPEG", response.getOutputStream());
		response.sendRedirect("pbimg.jsp?Picurl="/* + this.sPath + "/" */
				+ this.FileName + ".jpg&step=2"+pbid+"&"+(new Date().getTime()));		
    }        

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html; charset=utf-8");
		PrintWriter out = response.getWriter();

		// 登录检查
		Object zz = request.getSession().getAttribute("user1");

		if (zz == null) { // 先检查用户是否处于登入状态
			response.sendRedirect("logout.jsp");
			return;
		}

		String pbid = request.getQueryString();
		pbid = pbid==null?"":pbid;
		
		SmartUpload mySmartUpload = new SmartUpload();
		mySmartUpload.initialize(this.config, request, response);
		mySmartUpload.setMaxFileSize(2097152L);
		mySmartUpload.setAllowedFilesList("jpg,gif,png,jpeg,bmp");
		try {
			mySmartUpload.upload();
			File myFile = mySmartUpload.getFiles().getFile(0);
			String ext = myFile.getFileExt();
			// this.FileName = this.FileName + "." + ext;

			// 删除上次的同名文件

			//if (old.exists())
			//	old.delete();

			if (!(myFile.isMissing())) {
				 Date currTime = new Date();
				SimpleDateFormat formatter2 = new
				SimpleDateFormat("yyyyMMddhhmmssS", Locale.US);
				this.FileName = new	String(formatter2.format(currTime).getBytes("iso-8859-1"));

				myFile.saveAs("/" + this.sPath + "/" + this.FileName + "."
						+ ext, 1);
				//如果不是jpg，则另存为jpg
				if(!(ext.equalsIgnoreCase("jpg"))){
					java.io.File old = new java.io.File(request.getRealPath("/") + "/"
							+ this.sPath + "/" + this.FileName + "." + ext);
					java.io.File desimagefile = new java.io.File(request.getRealPath("/") + "/"
							+ this.sPath + "/" + this.FileName + "."+"jpg");
					
					ImageHepler.saveAsImageFile(old, desimagefile, true);
					
					if(old.exists())	old.delete();
				}
			}

			response.sendRedirect("pbimg.jsp?Picurl="/* + this.sPath + "/" */
					+ this.FileName + ".jpg&step=2&"+pbid+"&"+(new Date().getTime()));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void init(ServletConfig config) throws ServletException {
		this.config = config;
	}
}